#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    int minEatingSpeed(vector<int>& piles, int h) {
        int n = piles.size();
        int min = 1;
        int max = 0;
        for(int i = 0; i < n; i++)
        {
            if(piles[i] > max)
            {
                max = piles[i];
            }
        }

        // 二分查找
        int k = max;
        while(min < max)
        {
            int mid = min + (max-min)/2;

            int cost = eat(piles, mid);

            if(cost > h)
            {
                // 耗时过多，还需要右边找（速度增加）
                min = mid + 1;
            }
            else
            {
                // 可能左边还有符合条件的速度
                k = mid;
                max = mid;
            }


        }

        return k;
    }

    int eat(vector<int>& piles, int speed){
        int total = 0;
        for(int &num: piles)
        {
            // 进一法
            int hours = (num + speed - 1)/speed;
            total += hours;
        }

        return total;
    }
};


//int main()
//{
//    Solution solution;
////    [3,6,7,11] h=8 ret=4
//    vector<int> nums;
////    int h = 8;
////    nums.push_back(3);
////    nums.push_back(6);
////    nums.push_back(7);
////    nums.push_back(11);
////    [30,11,23,4,20] h=5 ret=30
////    int h = 5;
////    nums.push_back(30);
////    nums.push_back(11);
////    nums.push_back(23);
////    nums.push_back(4);
////    nums.push_back(20);
////    [2,2] h=4
//    int h = 4;
//    nums.push_back(2);
//    nums.push_back(2);
//    int ret = solution.minEatingSpeed(nums,h);
//    cout << "ret: " << ret << endl;
//}
